﻿
using System ;

using MskEdit.Dxf.Model ;
using MskEdit.Sdk ;


namespace MskEdit.Dxf.Backend
{

    public static class DxfIntReader
    {
        internal static int? TryParse( string valueStr, int lineNo, int? fallbackValue ) {
                
            int? maybeInt = SdkValueParser.TryParseToInt( valueStr, null ) ;
            if ( ! maybeInt.HasValue ) {
                SdkDiagnostics.TraceWarning( "Could not parse int value string.", lineNo ) ;
                return fallbackValue ;
            }
            
            return maybeInt ;
        }


        internal static int? TryRead( string codeStr, string[] allLines, ref int lineNo, int? fallbackValue ) {
        
            int internalLineNo = lineNo ;

            string valueStr = DxfLineReader.TryRead( codeStr, allLines, ref internalLineNo, null ) ;
            if ( valueStr == null ) {
                SdkDiagnostics.TraceWarning( "Could not read group code and int value string.", internalLineNo ) ;
                return fallbackValue ;
            }
            
            int? maybeInt = TryParse( valueStr, internalLineNo, null ) ;
            if ( ! maybeInt.HasValue )
                return fallbackValue ;
            
            lineNo = internalLineNo ;
            
            return maybeInt ;
        }
        
        
        internal static int? TryReadAfterCode( string[] allLines, ref int lineNo, int? fallbackValue )
        {
            int internalLineNo = lineNo ;
            
            string valueStr = DxfLineReader.TryRead( allLines, ref internalLineNo, null ) ;
            if ( valueStr == null ) {
                SdkDiagnostics.TraceWarning( "Could not read int value string.", internalLineNo ) ;
                return fallbackValue ;
            }
                 
            int? maybeInt = TryParse( valueStr, internalLineNo, null ) ;
            if ( ! maybeInt.HasValue )
                return fallbackValue ;
            
            lineNo = internalLineNo ;
            
            return maybeInt ;
        }


        internal static int? TryRead( string[] allLines, ref int lineNo, int? fallbackValue ) {
        
            int internalLineNo = lineNo ;
            
            DxfCode dxfCode = DxfCodeReader.TryRead( allLines, ref internalLineNo, null ) ;
            if ( dxfCode == null )
                return fallbackValue ;
            
            if ( ! dxfCode.HasIntCode )
                return fallbackValue ;
            
            int? maybeInt = TryReadAfterCode( allLines, ref internalLineNo, null ) ;
            if ( ! maybeInt.HasValue )
                return fallbackValue ;
                
            lineNo = internalLineNo ;
            
            return maybeInt ;
        }

    }
}
